package org.wk.news.service;

import com.google.common.base.Strings;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.wk.core.common.view.PageVo;
import org.wk.core.common.view.ResponseVo;
import org.wk.core.db.domain.IUser;
import org.wk.core.db.tool.WebUtils;
import org.wk.news.dao.NewsClassifiedsDao;
import org.wk.news.dao.NewsManageDao;
import org.wk.news.domain.NewsClassifieds;
import org.wk.news.domain.NewsManage;
import org.wk.news.enums.NewsStatus;
import org.wk.news.enums.NewsType;
import org.wk.news.view.NewsClassifiedsVo;
import org.wk.news.view.NewsManageVo;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName NewsManageServiceImpl
 * @Description
 * @Author ZhaoPing'an
 * @Date 2018/6/5 14:18
 */
@Service
public class NewsManageServiceImpl implements NewsManageService{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private NewsManageDao manageDao;
    @Autowired
    private NewsClassifiedsDao classifiedsDao;

    @Autowired
    private HttpServletRequest httpRequest;

    /**
     * @Description 资讯管理列表
     * @Param [params]
     * @author ZhaoPing'an
     * @Date 2018/6/6 9:27
     */
    @Override
    public PageVo findNewsManageListPage(Map<String, Object> params) {
        String newsTitle = (String)params.get("newsTitle");
        String temp = (String)params.get("page");
        Integer pageNo = temp==null?0:Integer.parseInt(temp)-1;
        temp = (String) params.get("limit");
        Integer pageSize = temp==null?10:Integer.parseInt(temp);
        NewsManage newsManage = new NewsManage();
        newsManage.setNewsTitle(newsTitle);
        //Page<NewsManage> page = manageDao.findAll(PageRequest.of(pageNo, pageSize));
        Page<NewsManage> page = manageDao.findAll(new Specification<NewsManage>() {
            @Override
            public Predicate toPredicate(Root<NewsManage> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if(null!=newsManage.getNewsTitle()&&!"".equals(newsManage.getNewsTitle())){
                    list.add(criteriaBuilder.like(root.get("newsTitle").as(String.class), "%"+newsManage.getNewsTitle()+"%"));
                }
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        }, PageRequest.of(pageNo,pageSize,new Sort(Sort.Direction.DESC,"createTime")));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<NewsManageVo> result = new ArrayList<>();
        for (NewsManage manage: page.getContent() ) {
            NewsManageVo manageVo = new NewsManageVo();
            BeanUtils.copyProperties(manage,manageVo);
            manageVo.setCreateTime(sdf.format(manage.getCreateTime()));
            result.add(manageVo);
        }
        PageVo pageVo = new PageVo<NewsClassifiedsVo>();
        pageVo.setTotal(page.getTotalElements());
        pageVo.setPageNo(++pageNo);
        pageVo.setPageSize(pageSize);
        pageVo.setResult(result);
        pageVo.setTotalPages(page.getTotalPages());
        return pageVo;
    }

    /**
     * @Description 保存资讯
     * @Param [manageVo]
     * @author ZhaoPing'an
     * @Date 2018/6/8 11:36
     */
    @Override
    public void insert(NewsManageVo manageVo) {
        Optional<NewsClassifieds> classifieds = classifiedsDao.findById(manageVo.getClassifiedId());
        NewsManage entity = new NewsManage();
        BeanUtils.copyProperties(manageVo,entity);
        entity.setTypeName(NewsType.containsCode(entity.getTypeCode()).getName());
        entity.setClassifiedsName(classifieds.get().getClassifiedsName());
        entity.setStatus(NewsStatus.NOT_PUBLISH.getCode());
        manageDao.save(entity);
    }

    /**
     * @Description 获取资讯详情
     * @Param [id]
     * @author ZhaoPing'an
     * @Date 2018/6/8 11:36
     */
    @Override
    public NewsManageVo findNewsInfo(String id) {
        NewsManageVo manageVo = new NewsManageVo();
        NewsManage result = manageDao.getOne(id);
        // 更新阅读量
        result.setPv(result.getPv()+1);
        manageDao.update(result);
        BeanUtils.copyProperties(result,manageVo);
        manageVo.setNewsId(result.getId());
        if (NewsType.VIDEO.getCode().equals(result.getTypeCode())) {
            String content = "<video width='100%'  controls preload='meta'  poster='"+result.getNewsCover()+"' x5-video-player-type='h5' x5-video-player-fullscreen='true' >\n" +
                    "    <source src='"+result.getVideoUrl() +"' type='video/mp4; codecs=\"avc1.42E01E, mp4a.40.2\"'></source>\n" +
                    "</video>";
//            String content = "<iframe src='"+result.getVideoUrl()+"'></iframe>";
            manageVo.setNewsContent(content);
        }
        manageVo.setReleaseTime(new DateTime(result.getCreateTime()).toString("yyyy-MM-dd"));
        return manageVo;
    }

    /**
     * @Description 修改资讯详情
     * @Param [newsManageVo]
     * @author ZhaoPing'an
     * @Date 2018/6/8 11:39
     */
    @Override
    public void update(NewsManageVo newsManageVo) {
        Optional<NewsClassifieds> classifieds = classifiedsDao.findById(newsManageVo.getClassifiedId());
        NewsManage entity = manageDao.getOne(newsManageVo.getId());
        BeanUtils.copyProperties(newsManageVo,entity);
        entity.setTypeName(NewsType.containsCode(newsManageVo.getTypeCode()).getName());
        entity.setClassifiedsName(classifieds.get().getClassifiedsName());
        manageDao.saveOrUpdate(entity);
    }

    /**
     * @Description 删除资讯
     * @Param [ids]
     * @author ZhaoPing'an
     * @Date 2018/6/8 11:42
     */
    @Override
    public void deleteBatchIds(List<String> ids) {
        manageDao.deleteByIdIn(ids);
    }

    /**
     * @Description 发布资讯
     * @Param [newsManageVo]
     * @author ZhaoPing'an
     * @Date 2018/6/13 16:12
     */
    @Override
    public void publish(NewsManageVo newsManageVo) {
        NewsManage entity = manageDao.getOne(newsManageVo.getId());
        entity.setStatus(NewsStatus.HAS_PUBLISH.getCode());
        manageDao.saveOrUpdate(entity);
    }

    /**
     * @Description 根据新闻资讯分类获取资讯分页列表
     * @Param [classifyId, pageNum, pageSize]
     * @author ZhaoPing'an
     * @Date 2018/6/9 13:53
     */
    @Override
    public ResponseVo findNewsByClassifies(int pageNum, int pageSize) {
        pageNum = pageNum<1?1:pageNum;
        pageNum -=1;
        pageSize = pageSize<1?10:pageSize;
        Page<NewsManage> result = manageDao.findAll(PageRequest.of(pageNum, pageSize));
        Map<String,Object> data = new HashMap<>();
        if (null!=result && !result.getContent().isEmpty()){
            data.put("total",result.getTotalElements());
            data.put("rows",result);
        } else {
            data.put("total",0);
            data.put("rows",new ArrayList<>());
        }
        return ResponseVo.success().setData(data);
    }

    /**
     * @Description 获取资讯分页列表
     * @Param [classifyId, pageNum, pageSize]
     * @author df.wu
     * @Date 2018/6/9 13:53
     * @return  newsId, newsTitle, newsCover, releaseTime, pv, detailUrl
     */
    @Override
    public ResponseVo findNews(int pageNum, int pageSize) {
        pageNum = pageNum<1?1:pageNum;
        pageNum -=1;
        pageSize = pageSize<1?10:pageSize;
        Page<NewsManage> managePage = manageDao.findAll(new Specification<NewsManage>() {
            @Override
            public Predicate toPredicate(Root<NewsManage> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                list.add(criteriaBuilder.equal(root.get("status").as(String.class), NewsStatus.HAS_PUBLISH.getCode()));
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        }, PageRequest.of(pageNum,pageSize,new Sort(Sort.Direction.DESC,"createTime")));

        /*Page<NewsManage> managePage = manageDao.findAll(PageRequest.of(pageNum, pageSize));*/
        Map<String,Object> resData = new HashMap<>();
        List<Map> rows = new ArrayList<>();
        if (null!=managePage && !managePage.getContent().isEmpty()){
            logger.info("请求地址========{}",httpRequest.getRequestURL().toString());
            String requestUrl = httpRequest.getRequestURL().toString();
            IUser user = WebUtils.getUser();
            String userId = null;
            if (user!=null) {
                userId = user.getId();
            }
            resData.put("total",managePage.getTotalElements());
            for (NewsManage news: managePage) {
                Map<String, Object> temp = new HashMap<>();
                temp.put("newsId", news.getId());
                temp.put("newsTitle", news.getNewsTitle());
                temp.put("newsCover", news.getNewsCover());
                temp.put("releaseTime", new DateTime(news.getCreateTime()).toString("yyyy-MM-dd"));
                temp.put("pv", news.getPv());
                temp.put("typeCode", news.getTypeCode());
                if (userId==null) {
                    temp.put("detailUrl", requestUrl+"/"+news.getId());
                } else {
                    temp.put("detailUrl", requestUrl+"/"+news.getId()+"?userId="+userId);
                }
                rows.add(temp);
            }
            resData.put("rows",rows);
        } else {
            resData.put("total",0);
            resData.put("rows",rows);
        }
        return ResponseVo.success().setData(resData);
    }

    /**
     * 获取分享信息
     *
     * @param newsId 新闻ID
     * @return
     */
    @Override
    public ResponseVo findShareInfoByNewsId(String newsId) {
        NewsManage newsManage = manageDao.getOne(newsId);

        logger.info("请求地址========{}",httpRequest.getRequestURL().toString());
        String requestUrl = httpRequest.getRequestURL().toString();
        requestUrl = requestUrl.replaceAll("/share_info","");
        Map<String,String> resData = new HashMap<>();
        resData.put("share_title",newsManage.getNewsTitle());
        resData.put("share_image","http://img.qiniu.vp359.com/share-logo.png");
        resData.put("share_desc",newsManage.getProfile());
        resData.put("share_link",requestUrl);

        return ResponseVo.success().setData(resData);
    }
}
